<?php

namespace addons\sum\controller;


use addons\sum\controller\Base;
use addons\sum\model\User;
use addons\sum\model\UserWalletLog;

class UserWallet extends Base
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    // 财务流水
    public function index()
    {
        $wallet_type = $this->request->param('wallet_type', 'commission');//commission=佣金流水
        $type = $this->request->param('type');//流水类型
        $list_rows = $this->request->param('list_rows', 10);
        $user = User::info();
        $where['user_id'] = $user->id;
        if($type){
            if($type=='admin_recharge'){
                $where['type'] = ['in',['admin_recharge','admin_deduct']];
            }else{
                $where['type'] = $type;
            }


        }
        $list=UserWalletLog::where($where)->{$wallet_type}()->order('createtime', 'desc')->paginate($list_rows);
        $list->each(function ($item){
            if($item['related_user_id']>0){
                $item['related_user']=User::field("id,oil_num,avatar,mobile")->where('id',$item['related_user_id'])->find();
            }else{
                $item['related_user']=null;
            }
            if($item['ext']){
                $item['ext_arr']=json_decode($item['ext'],true);
            }else{
                $item['ext_arr']=null;
            }
            if(empty($item['ext_arr'])){
                $item['ext_arr']=null;
            }
        });
        $this->success('获取成功', ['list' => $list]);
    }

    //余额互转
    public function mutual(){
        $user = User::info();
        $to_user_num = $this->request->post('to_user_num');
        $to_user=User::where('oil_num',$to_user_num)->whereOr('mobile',$to_user_num)->find();
        if(!$to_user){
            $this->error('没有该用户',$to_user_num);
        }
        if($user['id']==$to_user['id']){
            $this->error('不能向自己转账');
        }
        $money = $this->request->post('money');
        if ($user->money < $money) {
            $this->error('可用余额不足');
        }
        $res = \think\Db::transaction(function () use ($money,$user,$to_user) {
            try {
                // 扣除用户余额
                User::money(-$money, $user->id, 'mutual_red', $to_user->id,'','',$to_user->id);
                // 增加相关用户余额
                User::money($money, $to_user->id, 'mutual_add', $user->id,'','',$user->id);
                return true;
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        });
        if($res) {
            $this->success('操作成功');
        }
        $this->error('操作失败');
    }
}
